const PENDING = 'pending'
const RESLOVE = 'resloved'
const REJECT = 'rejected'

function myPromise (cb){
    const that = this
    that.status = PENDING
    that.resloveCallback = []
    that.rejectCallback = []

    function reslove(value){
        if(that.status = PENDING){
            that.status = RESLOVE
            that.value=value
            that.resloveCallback.forEach(item => item(that.value))
        }
    }
    function reject(value){
        if(that.status = PENDING){
            that.status = REJECT
            that.value=value
            that.rejectCallback.forEach(item => item(that.value))
        }
    }
    try{
        cb(reslove,reject)
    }catch(e){
        reject(e)
    }
}

myPromise.prototype.then=function(onResloved,onRejected){
    const that = this
    typeof onResloved =='function' ?  onResloved: value => value
    typeof onRejected =='function' ?  onRejected: err => {throw value}

    if(that.status == RESLOVE){
        onResloved(that.value)
    }
    if(that.status == REJECT){
        onRejected(that.value)
    }

    if(that.status == PENDING){
        that.resloveCallback.push(onResloved)
        that.rejectCallback.push(onRejected)
    }
    
}